<script setup lang="ts">
import type { UploadType } from "@@/constants/other-keys"
import type { FormInstance, FormRules, UploadUserFile } from "element-plus"
import { ElMessage, ElMessageBox } from "element-plus"
import { cloneDeep, isEqual } from "lodash-es"
import { computed, ref, watch } from "vue"

interface Props {
  id: string | undefined
  visible: boolean
}

const props = defineProps<Props>()
const emit = defineEmits(["closeDialog"])
const DEFAULT_FORM_DATA: any = {
  sim_engine_id: undefined,
  agent_name: "",
  agent_type: "",
  agent_path: "",
  agent_support_side: "3",
  agent_describe: "",
  agent_image_id: ""
}
const dialogVisible = ref<boolean>(false)
const formRef = ref<FormInstance | null>(null)
const formData = ref<any>(cloneDeep(DEFAULT_FORM_DATA))
const formRules: FormRules<any> = {
  agent_name: [{ required: true, trigger: "blur", message: "请输入引擎名称" }]
}
const fileList = ref<UploadUserFile[]>([])
const loading = ref<boolean>(false)
const detailLoading = ref<boolean>(false)
const uploadType = ref<UploadType>()
const isEdit = ref<boolean>(false)
const defaultFormData = ref<any>(cloneDeep(DEFAULT_FORM_DATA))
const agentTypeOptions = ref<string[]>([])

const textMap = computed(() => {
  return "另存为"
})
function getAgentInfo() {
  detailLoading.value = true
  // props.id
  // && getAgentInfoApi(props.id)
  //   .then(({ data }) => {
  //     if (data) {
  //       formData.value = cloneDeep(data)
  //       formData.value.agent_path = data.agent_files_path
  //       formData.value.agent_support_side = `${data.agent_support_side}`

  //       defaultFormData.value = cloneDeep(formData.value)
  //     } else {
  //       ElMessage("数据不存在")
  //     }
  //   })
  //   .finally(() => {
  //     detailLoading.value = false
  //   })
}
function showDialog() {
  formRef.value?.resetFields()
  fileList.value = []
  isEdit.value = false
  detailLoading.value = false
  getAgentInfo()
}
function closeDialog() {
  formRef.value?.resetFields()
  emit("closeDialog", undefined)
}
function handleConfirm() {
  formRef.value?.validate(async (valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const params = {
      sim_engine_id: formData.value.sim_engine_id,
      agent_name: formData.value.agent_name,
      describe: formData.value.agent_describe
    }
    // saveCopyApi(params)
    //   .then(() => {
    //     ElMessage.success("操作成功")
    //     emit("closeDialog", "refresh")
    //   })
    //   .finally(() => {
    //     loading.value = false
    //   })
  })
}
function handleCloseTip(done: () => void) {
  // 校验值是否相同
  if (isEqual(defaultFormData.value, formData.value)) {
    closeDialog()
    done()
    return
  }
  ElMessageBox.confirm("当前编辑未保存，是否确定关闭？").then(() => {
    done()
  })
}

watch(
  () => [props.id, props.visible],
  () => {
    dialogVisible.value = props.visible
    if (props.visible) {
      showDialog()
    }
  }
)
watch(
  () => fileList.value,
  () => {
    if (fileList.value.length > 0) {
      formData.value.agent_path = fileList.value[0].name
    }
  }
)
watch(
  () => fileList.value,
  () => {
    if (uploadType.value != undefined && fileList.value.length > 0) {
      if (uploadType.value == "File") {
        const files = fileList.value as UploadUserFile[]
        formData.value.agent_path = files[0].name
      }
      if (uploadType.value == "Folder") {
        // 文件夹
        const files = fileList.value as File[]
        const relativePath = files[0].webkitRelativePath
        const folderName = relativePath && relativePath.split("/")[0]
        formData.value.agent_path = folderName
      }
    } else {
      formData.value.agent_path = ""
    }
  },
  { deep: true }
)

onMounted(() => {
  // getAgentTypeOptionsApi().then(({ data }) => {
  //   agentTypeOptions.value = data.type
  // })
})
</script>

<template>
  <el-drawer
    v-model="dialogVisible"
    direction="rtl"
    size="600px"
    @close-auto-focus="closeDialog"
    @close="closeDialog"
    :before-close="handleCloseTip"
    :show-close="false"
    :append-to-body="true"
  >
    <template #header>
      <div class="drawer-header">
        <h4>{{ textMap }}</h4>
      </div>
    </template>
    <template #default>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        width="600"
        label-width="120px"
        label-position="right"
        :close-on-click-modal="false"
        v-loading="detailLoading"
      >
        <el-form-item label="引擎名称" prop="sim_engine_name">
          <el-input v-model="formData.sim_engine_name" autocomplete="off" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="引擎描述" prop="sim_engine_describe">
          <el-input
            v-model="formData.sim_engine_describe"
            :rows="3"
            type="textarea"
            placeholder="可以输入智能体的基本逻辑，应用场景等信息，最多输入600字"
            maxlength="600"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button plain v-throttle="() => closeDialog()">
          取 消
        </el-button>
        <el-button :loading="loading" type="primary" v-throttle="() => handleConfirm()">
          确 定
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style lang="scss" scoped>
.upload-demo {
  width: 100% !important;
}
:deep(.el-upload.el-upload--text) {
  width: 100% !important;
}
</style>
